package com.lnj.messages.servise;

import com.lnj.messages.quarzJob.OrdersJob;
import com.lnj.utils.OrderMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

@Service
@RequiredArgsConstructor
@Slf4j
public class OrderDelayService {
    @Autowired
    private final Scheduler quartzScheduler;

    // 处理订单创建事件
    @Transactional
    public void handleOrderCreated(OrderMessage event) {
        // 15分钟后发送提醒
        scheduleJob(event.getOrderId(), "REMIND", event.getCreateTime().plusMinutes(15));

        // 30分钟后取消订单
        scheduleJob(event.getOrderId(), "CANCEL", event.getCreateTime().plusMinutes(30));
    }

    // 处理支付成功事件
    public void handleOrderPaid(OrderMessage event) throws SchedulerException {
        // 取消所有相关任务
        quartzScheduler.deleteJob(new JobKey("remind_" + event.getOrderId()));
        quartzScheduler.deleteJob(new JobKey("cancel_" + event.getOrderId()));
    }

    //创建定时任务
    private void scheduleJob(Long orderId, String action, LocalDateTime executeTime) {
        try {
            JobDetail job = JobBuilder.newJob(OrdersJob.class)
                    .withIdentity(action.toLowerCase() + "_" + orderId)//设置job的唯一标识
                    .usingJobData("orderId", orderId)
                    .usingJobData("action", action)
                    .build();

            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(action.toLowerCase() + "_trigger_" + orderId)
                    .startAt(Date.from(executeTime.atZone(ZoneId.systemDefault()).toInstant()))
                    .build();
            log.info("创建定时任务:{}",job.getKey(),action);
            quartzScheduler.scheduleJob(job, trigger);
        } catch (SchedulerException e) {
            throw new RuntimeException("Failed to schedule job", e);
        }
    }
}